package com.imay.live.adapter;

import android.support.v4.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.imay.live.R;
import com.imay.live.activity.family.helper.session.extension.DynamicsAttachment;
import com.imay.live.activity.family.helper.session.extension.LiveAttachment;
import com.imay.live.activity.family.helper.session.extension.ShortLiveAttachment;
import com.imay.live.heartlikeslib.swipelayout.SwipeHorizontalMenuLayout;
import com.imay.live.helper.LevelHelper;
import com.imay.live.helper.SystemNoticeHelper;
import com.imay.live.logic.ChatTimeLogic;
import com.imay.live.model.RecentContactInfo;
import com.imay.live.model.RecentFamilyModel;
import com.imay.live.model.SystemNoticeModel;
import com.imay.live.utils.GlideUtil;
import com.imay.base.util.SpannableStringUtils;
import com.imay.live.utils.ImayLogUtil;
import com.imay.live.utils.TimeUtil;
import com.imay.live.view.dialog.ShowAdsFragment;
import com.netease.nim.uikit.NimUIKit;
import com.netease.nim.uikit.cache.TeamDataCache;
import com.netease.nim.uikit.common.ui.imageview.HeadImageView;
import com.netease.nim.uikit.recent.TeamMemberAitHelper;
import com.netease.nim.uikit.session.helper.TeamNotificationHelper;
import com.netease.nim.uikit.team.helper.TeamExtendHelper;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.avchat.constant.AVChatRecordState;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.avchat.model.AVChatAttachment;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.attachment.NotificationAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.team.model.Team;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by  nick on 2017/5/5 0005.
 * 私信列表
 */

public class RecentContactAdapter extends BaseQuickAdapter<MultiItemEntity, BaseViewHolder> {

    public static final int SYSTEM = 1;
    public static final int USER = 2;
    public static final int FAMILY = 3;
    private static final String KEY_AIT = "ait";


    public RecentContactAdapter(List<MultiItemEntity> data) {
        super(R.layout.item_recent_contact,data);
    }



    @Override
    protected void convert(BaseViewHolder helper, MultiItemEntity item) {

        switch (item.getItemType()){
            case USER:
                bindUserItem(helper, (RecentContactInfo) item);
                break;
            case SYSTEM:
                bindSystemNoticeItem(helper, (SystemNoticeModel) item);
                break;
            case FAMILY:
                bindFamilyItem(helper, (RecentFamilyModel) item);
                break;

        }

    }

    private void bindSystemNoticeItem(BaseViewHolder helper, SystemNoticeModel item) {
        SystemNoticeModel info = item;
        SwipeHorizontalMenuLayout menuLayout = helper.getView(R.id.sml_system_notice);
        helper.setVisible(R.id.iv_head_img_recent_contact, true);
        helper.setVisible(R.id.iv_head_img_recent_family, false);
        helper.setVisible(R.id.tv_unread_recent_family, false);
        menuLayout.setSwipeEnable(false);
        if (info.getCreateTime() == 0) {
            helper.setVisible(R.id.tv_time_recent_contact, false);
            helper.setVisible(R.id.tv_content_recent_contact, false);
            helper.setVisible(R.id.tv_user_level_recent_contact, false);
            int imageId = R.mipmap.ico_05_xttongzhi_zanwuxitongtongzhi;
            helper.setImageResource(R.id.iv_head_img_recent_contact, imageId);
            helper.setVisible(R.id.tv_unread_recent_contact, false);
            helper.setText(R.id.tv_name_recent_contact, R.string.mine_system_no_notice);
        } else {
            helper.setVisible(R.id.tv_user_level_recent_contact, false);
            helper.setVisible(R.id.tv_time_recent_contact, true);
            helper.setVisible(R.id.tv_content_recent_contact, true);
            helper.setText(R.id.tv_time_recent_contact, TimeUtil.getFormatTime(info.getCreateTime()));
            int imageId = R.mipmap.ico_05_xttongzhi_xitongtongzhi;
            helper.setText(R.id.tv_name_recent_contact, R.string.mine_system_notice);
            helper.setImageResource(R.id.iv_head_img_recent_contact, imageId);
            helper.setVisible(R.id.tv_unread_recent_contact, info.getUnReadNum() > 0);
            int stringId = SystemNoticeHelper.getTextByType(info.getContentType());
            if (info.getContentId() == 0) {
                helper.setText(R.id.tv_content_recent_contact, mContext.getString(stringId) + "：" + info.getContent());
            } else {
                helper.setText(R.id.tv_content_recent_contact, mContext.getString(stringId) + "：" + SystemNoticeHelper.getContent(mContext, info.getContentType(), (int) info.getContentId(), info.getContentParameters()));
            }
        }
    }

    private void bindUserItem(BaseViewHolder helper, RecentContactInfo item) {
        RecentContactInfo info = item;
        SwipeHorizontalMenuLayout menuLayout = helper.getView(R.id.sml_system_notice);
        menuLayout.setSwipeEnable(true);
        ImageView iv_head_img_system_notice = helper.getView(R.id.iv_head_img_recent_contact);
        GlideUtil.loadCircleImage(iv_head_img_system_notice,info.getYourImgHead(), R.mipmap.pnl_00_head108);
        helper.setText(R.id.tv_name_recent_contact, info.getYourNick());
        helper.setText(R.id.tv_content_recent_contact, info.getLatestMsg());
        helper.setVisible(R.id.tv_time_recent_contact, true);
        helper.setText(R.id.tv_time_recent_contact, ChatTimeLogic.getMessageTime(info.getLatestMsgTime()));
        helper.setVisible(R.id.tv_unread_recent_contact, info.getUnReadRecordCount() > 0);
        helper.addOnClickListener(R.id.tv_system_notice_delete);
        helper.setVisible(R.id.tv_user_level_recent_contact, true);
        helper.setText(R.id.tv_user_level_recent_contact, info.getYourUserLv() + "");
        helper.setBackgroundRes(R.id.tv_user_level_recent_contact, LevelHelper.getUserLevelResId(info.getYourUserLv()));
        helper.setImageResource(R.id.iv_vip, LevelHelper.getVIPIcon(info.getYourVip()));
        helper.setVisible(R.id.iv_head_img_recent_contact, true);
        helper.setVisible(R.id.iv_head_img_recent_family, false);
        helper.setVisible(R.id.tv_unread_recent_family, false);
    }
    private void bindFamilyItem(BaseViewHolder helper, RecentFamilyModel item) {
        RecentFamilyModel recent = item;
        SwipeHorizontalMenuLayout menuLayout = helper.getView(R.id.sml_system_notice);
        menuLayout.setSwipeEnable(true);
        HeadImageView headImageView = helper.getView(R.id.iv_head_img_recent_family);
        Team team = TeamDataCache.getInstance().getTeamById(recent.getContactId());
        headImageView.loadTeamIconByTeam(team);
        SpannableStringBuilder teamName = SpannableStringUtils.getBuilder(mContext.getString(R.string.recent_contact_family)).setForegroundColor(mContext.getResources().getColor(R.color.text_f56)).append( TeamDataCache.getInstance().getTeamName(recent.getContactId())).create();
        helper.setText(R.id.tv_name_recent_contact, teamName);
        if (TeamExtendHelper.isFamilyLocked(recent.getContactId())){
            helper.setText(R.id.tv_content_recent_contact, R.string.family_locked);
        }else{
            String content = getContent(recent);
            if (hasAitExtension(recent)) {
                if (recent.getUnreadCount() == 0) {
                    helper.setText(R.id.tv_content_recent_contact, content);
                    clearRecentContactAited(recent.getContactId());
                } else {
                    SpannableStringBuilder builder = SpannableStringUtils.getBuilder(mContext.getString(R.string.ait_me)).setForegroundColor(ContextCompat.getColor(mContext, R.color.text_f82)).append(content).create();
                    helper.setText(R.id.tv_content_recent_contact, builder);

                }
            }else{
                helper.setText(R.id.tv_content_recent_contact, content);
            }
        }
        helper.setVisible(R.id.tv_time_recent_contact, true);
        helper.setText(R.id.tv_time_recent_contact,  com.netease.nim.uikit.common.util.sys.TimeUtil.getTimeShowString(recent.getTime(), true));
        helper.setVisible(R.id.tv_unread_recent_contact, false);
        helper.setVisible(R.id.tv_unread_recent_family, recent.getUnreadCount()>0);
        helper.setText(R.id.tv_unread_recent_family, recent.getUnreadCount()>999?"999+":recent.getUnreadCount()+"");
        helper.setBackgroundRes(R.id.tv_user_level_recent_contact,R.mipmap.ico_dajiazutubiao);
        int level = TeamExtendHelper.getFamilyLv(recent.getContactId());
        if (level!=-1){
            helper.setText(R.id.tv_user_level_recent_contact,level+"");
        }
        helper.addOnClickListener(R.id.tv_system_notice_delete);
        helper.setVisible(R.id.iv_head_img_recent_contact, false);
        helper.setVisible(R.id.iv_head_img_recent_family, true);
//        if (TeamMemberAitHelper.hasAitExtension(content)) {
//            if (recent.getUnreadCount() == 0) {
//                TeamMemberAitHelper.clearRecentContactAited(recent);
//            } else {
//                content = TeamMemberAitHelper.getAitAlertString(content);
//            }
//        }
//    }
    }

    protected String descOfMsg(RecentFamilyModel recent) {
        if (recent.getMsgType() == MsgTypeEnum.text) {
            return recent.getContent();
        } else if (recent.getMsgType() == MsgTypeEnum.tip) {
            String digest = null;
//            if (getCallback() != null) {
//                digest = getCallback().getDigestOfTipMsg(recent);
//            }

            if (digest == null) {
                digest = getDefaultDigest(null, recent);
            }

            return digest;
        } else if (recent.getAttachment() != null) {
            String digest = null;
//            if (getCallback() != null) {
//                digest = getCallback().getDigestOfAttachment(recent, recent.getAttachment());
//            }

            if (digest == null) {
                digest = getDefaultDigest(recent.getAttachment(), recent);
            }

            return digest;
        }
        return "";
    }

    private String getContent(RecentFamilyModel recent){
        String content = descOfMsg(recent);

        String fromId = recent.getFromAccount();
        if (!TextUtils.isEmpty(fromId)
                && !fromId.equals(NimUIKit.getAccount())
                && !(recent.getAttachment() instanceof NotificationAttachment)) {
            String tid = recent.getContactId();
            String teamNick = getTeamUserDisplayName(tid, fromId);
            content = teamNick + ": " + content;
//            if (hasAitExtension(recent)) {
//                if (recent.getUnreadCount() == 0) {
//                    clearRecentContactAited(recent.getContactId());
//                } else {
//                    content = TeamMemberAitHelper.getAitAlertString(content);
//                }
//            }
        }

        return content;
    }

    // SDK本身只记录原始数据，第三方APP可根据自己实际需求，在最近联系人列表上显示缩略消息
    // 以下为一些常见消息类型的示例。
    private String getDefaultDigest(MsgAttachment attachment, RecentFamilyModel recent) {
        switch (recent.getMsgType()) {
            case text:
                return recent.getContent();
            case image:
                return "发布了[图片]";
            case video:
                return "发布了[视频]";
            case audio:
                return "发布了[语音]";
            case location:
                return "[位置]";
            case file:
                return "[文件]";
            case tip:
                List<String> uuids = new ArrayList<>();
                uuids.add(recent.getRecentMessageId());
                List<IMMessage> messages = NIMClient.getService(MsgService.class).queryMessageListByUuidBlock(uuids);
                if (messages != null && messages.size() > 0) {
                    return messages.get(0).getContent();
                }
                return "[通知提醒]";
            case notification:
                return TeamNotificationHelper.getTeamNotificationText(recent.getContactId(),
                        recent.getFromAccount(),
                        (NotificationAttachment) recent.getAttachment());
            case avchat:
                AVChatAttachment avchat = (AVChatAttachment) attachment;
                if (avchat.getState() == AVChatRecordState.Missed && !recent.getFromAccount().equals(NimUIKit.getAccount())) {
                    // 未接通话请求
                    StringBuilder sb = new StringBuilder("[未接");
                    if (avchat.getType() == AVChatType.VIDEO) {
                        sb.append("视频电话]");
                    } else {
                        sb.append("音频电话]");
                    }
                    return sb.toString();
                } else if (avchat.getState() == AVChatRecordState.Success) {
                    StringBuilder sb = new StringBuilder();
                    if (avchat.getType() == AVChatType.VIDEO) {
                        sb.append("[视频电话]: ");
                    } else {
                        sb.append("[音频电话]: ");
                    }
                    sb.append(com.netease.nim.uikit.common.util.sys.TimeUtil.secToTime(avchat.getDuration()));
                    return sb.toString();
                } else {
                    if (avchat.getType() == AVChatType.VIDEO) {
                        return ("[视频电话]");
                    } else {
                        return ("[音频电话]");
                    }
                }
            case robot:
                return "[机器人消息]";
            case custom:
                if (attachment instanceof DynamicsAttachment){
                    return "发布了[动态]";
                }else if(attachment instanceof ShortLiveAttachment){
                    return "完成了[超胆播]";
                }else if(attachment instanceof LiveAttachment){
                    return "开始[直播]了";
                }
                return "[自定义消息] ";
            default:
                return "[自定义消息] ";
        }
    }

    private String getTeamUserDisplayName(String tid, String account) {
        return TeamDataCache.getInstance().getTeamMemberDisplayName(tid, account);
    }

    public static boolean hasAitExtension(RecentFamilyModel recentContact) {
        if (recentContact == null || recentContact.getSessionType() != SessionTypeEnum.Team) {
            return false;
        }
        Map<String, Object> ext = recentContact.getExtension();
        if (ext == null) {
            return false;
        }
        List<String> mid = (List<String>) ext.get(KEY_AIT);

        return mid != null && !mid.isEmpty();
    }


    private void clearRecentContactAited(final String contactId) {
        // 查询最近联系人列表数据
        NIMClient.getService(MsgService.class).queryRecentContacts().setCallback(new RequestCallbackWrapper<List<RecentContact>>() {

            @Override
            public void onResult(int code, List<RecentContact> recents, Throwable exception) {
                if (code != ResponseCode.RES_SUCCESS || recents == null) {
                    return;
                }
                for (RecentContact contact:recents) {
                    if (contact.getContactId().equals(contactId)){
                        TeamMemberAitHelper.clearRecentContactAited(contact);
                        break;
                    }
                }
            }
        });
    }

}
